<?php
/***


//

useage:
$image = new ImageResize($newfilename); //图片名称
$image->PicDir = 'data/images/thumb_s/'; // 图片的路径
$image->TmpName = 'data/images/imgname.jpg';// ԭͼ��ַ
$image->newWidth = $image->newHeight = 100; // 宽高的最大值，将等比例缩略
$image->resize();

*/
class ImageResize {
	var $FileName;
	var $newWidth = 100; // new width
	var $newHeight = 100; //new height
	var $TmpName;
	var $PicDir;  //store uploaded images
	var $ImageQuality = 90;  // image compression (max value 100) 使用imagejpeg函数时，60的图片大小比80时要小

	function ImageResize($FileName='') {
		$this->FileName= $FileName;
	}
	
	function setQuality($quality){
		$this->ImageQuality = $quality;
	}
	
	function watermark_text( $src_img,$waterText,$pos,$options = array() ) {
		if(!class_exists('Imagick') || empty($pos)) {
			return false;
		}
		$this->image = new Imagick( $src_img );

		$_options = array(
			'size' => 16,
			'font' => 'Microsoft-YaHei',
			'color' => '#FFF',
			'poshori' => 20,
			'posvert' => 10
		);
		$options = array_merge($_options,$options);
		
		$draw = new ImagickDraw();
		$draw->setFont($options['font']);
		$draw->setFontSize($options['size']);//设置字体大小
		$draw->setTextUnderColor(new ImagickPixel ('transparent'));//设置背景色
		$draw->setFillColor (new ImagickPixel($options['color']));//设置字体颜色
		
		if($pos==1) { $gravity = imagick::GRAVITY_NORTHWEST;}
		elseif($pos==2) { $gravity = imagick::GRAVITY_NORTH;}
		elseif($pos==3) { $gravity = imagick::GRAVITY_NORTHEAST;}
		elseif($pos==4) { $gravity = imagick::GRAVITY_WEST;}
		elseif($pos==5) { $gravity = imagick::GRAVITY_CENTER;}
		elseif($pos==6) { $gravity = imagick::GRAVITY_EAST;}
		elseif($pos==7) { $gravity = imagick::GRAVITY_SOUTHWEST;}
		elseif($pos==8) { $gravity = imagick::GRAVITY_SOUTH;}
		elseif($pos==9) { $gravity = imagick::GRAVITY_SOUTHEAST;}

		$draw->setGravity($gravity);//设置水印位置
		$draw->setFillAlpha(0.9);
		$draw->annotation($options['poshori'], $options['posvert'], $waterText);
		
		$this->image->drawImage($draw);
		
		$this->image->writeImage($src_img);
		$this->image->clear();
		$this->image->destroy();
	}
	
	function watermark( $src_img,$watermark_img,$pos ) {
		if(!class_exists('Imagick')) {
			return false;
		}
		if(!is_valid_url($watermark_img)) {
			return false;
		}
		
		$this->image = new Imagick( $src_img );
		
		$src_width = $this->image->getImageWidth();
		$src_height = $this->image->getImageHeight();
		
		if($src_width < 100 || $src_height < 100 ) {
			return false;
		}
		
		$watermark = new Imagick($watermark_img);
		$watermark->setImageFormat("png");
		//$watermark->setBackgroundColor(new ImagickPixel('transparent')); 
		//$watermark->setImageOpacity(0.7); // 设置透明度0.7
		$water_width = $watermark->getImageWidth();
		$water_height = $watermark->getImageHeight();

		if($water_width < 10 || $water_width < 10 ) {
			return false;
		}
		
		$x = 20; $y = 20;
		if( in_array($pos,array(4,5,6))) { $y = ($src_height - $water_height)/2; }
		if( in_array($pos,array(7,8,9))) { $y = $src_height - $water_height - 15; }
		
		if( in_array($pos,array(2,5,8))) { $x = ($src_width - $water_width)/2; }
		if( in_array($pos,array(3,6,9))) { $x = $src_width - $water_width - 15; }
		
		$draw = new ImagickDraw();
		$draw->composite($watermark->getImageCompose(), $x, $y, $water_width, $water_height, $watermark);
		//$draw->setFillOpacity(0.8);
		
		$type = strtolower($this->image->getImageFormat());
		
		if( $type=='gif' ) {
			$image = $this->image;
			$canvas = new Imagick();
			$images = $image->coalesceImages();
			foreach($images as $frame)
			{
				$img = new Imagick();
				$img->readImageBlob($frame);
				$img->drawImage($draw);
		
				$canvas->addImage( $img );
				$canvas->setImageDelay( $img->getImageDelay() );
			}
			$image->destroy();
			$this->image = $canvas;
		}
		else {
			$this->image->drawImage($draw);
		}
		$this->image->writeImage($src_img);
		$this->image->clear();
		$this->image->destroy();
	}
	
	function resizefile($src_img,$target_img,$width=1000,$height=9999){
	    
	    if( function_exists('exif_imagetype') ){
	        $exif_type = @exif_imagetype($src_img);
	        if($exif_type==IMAGETYPE_GIF){
	            $ext = 'gif';
	        }
	        elseif($exif_type==IMAGETYPE_JPEG){
	            $ext = 'jpg';
	        }
	        elseif($exif_type==IMAGETYPE_PNG){
	            $ext = 'png';
	        }
	        elseif($exif_type==IMAGETYPE_BMP){
	            $ext = 'bmp';
	        }
	    }
	    if(empty($ext)){
    		$ext = explode(".",$src_img);
    		$ext = end($ext);
    		$ext = strtolower($ext);
	    }
		if(!in_array($ext,array('jpg','jpeg','bmp','gif','png'))){
			return false;
		}
		$this->newWidth = $width;
		$this->newHeight = $height;
		
		list($width_orig, $height_orig) = getimagesize($src_img);
		if(!$width_orig || !$height_orig){
			return false;
		}
		
		$ratio_orig = $width_orig/$height_orig;
		if ($this->newHeight && $this->newWidth/$this->newHeight > $ratio_orig) {
			$this->newWidth = intval($this->newHeight*$ratio_orig);
		} else {
			$this->newHeight = intval($this->newWidth/$ratio_orig);
		}
		
		if($width_orig < $this->newWidth && $height_orig < $this->newHeight){ //图片尺寸小，不会放大，直接返回。
			return false;
		}
		
		if (defined('SAE_MYSQL_DB')) {
			$img = new SaeImage();
			$img->setData( file_get_contents($src_img) );
			$img->resize($this->newWidth,$this->newHeight);
			$new_data = $img->exec();
			file_put_contents($target_img, $new_data);
		}
		else{
			$normal  = imagecreatetruecolor($this->newWidth, $this->newHeight);
			if($ext == "jpg") {
				$source = @imagecreatefromjpeg($src_img);
			}
			else if($ext == "gif") {
				$source = @imagecreatefromgif ($src_img);
			}
			else if($ext == "png"){
				$this->ImageQuality = 9;
				$source = @imagecreatefrompng ($src_img);
			}
			if( empty($source) ){
			    CakeLog::error('ImageResize::resize() error. image ext error. The ext is '.$ext);
			    return false;
			}
		
			imagecopyresampled($normal, $source,    0, 0, 0, 0, $this->newWidth, $this->newHeight, $width_orig, $height_orig);
			if($ext == "jpg") {
				imagejpeg($normal,$target_img, "$this->ImageQuality");
			}
			else if($ext == "gif") {
				imagegif ($normal,$target_img); //, "$this->ImageQuality" gif不支持quality参数
			}
			else if($ext == "png") {
				imagepng ($normal,$target_img, "$this->ImageQuality");
			}
			imagedestroy($source);
		}
	}
	
	function resize() {

        if( function_exists('exif_imagetype') ){
            $exif_type = @exif_imagetype($this->TmpName);
            if($exif_type==IMAGETYPE_GIF){
                $ext = 'gif';
            }
			elseif($exif_type==IMAGETYPE_JPEG){
                $ext = 'jpg';
            }
			elseif($exif_type==IMAGETYPE_PNG){
                $ext = 'png';
            }
			elseif($exif_type==IMAGETYPE_BMP){
                $ext = 'bmp';
            }
        }

        if(empty($ext)){
            $ext = explode(".",$this->TmpName);
            $ext = end($ext);
            $ext = strtolower($ext);
        }
        if( $ext == "png" || $ext == "gif" ){
            return false;
        }
        list($width_orig, $height_orig) = @getimagesize($this->TmpName);

        $ratio_orig = $width_orig/$height_orig;

        if ($this->newHeight && $this->newWidth/$this->newHeight > $ratio_orig) {
            $this->newWidth = intval($this->newHeight*$ratio_orig);
        } else {
            $this->newHeight = intval($this->newWidth/$ratio_orig);
        }

        if($width_orig < $this->newWidth && $height_orig < $this->newHeight){ //图片尺寸小，不会放大，直接返回。
            //不返回，仍然进行处理。将图片的清晰度降低，压缩图片。
            $this->newWidth = $width_orig;
            $this->newHeight = $height_orig;
        }
        if(empty($this->newWidth) || empty($this->newHeight)) {
            return false;
        }
		
		if(class_exists('Imagick')) {
		    $image = new Imagick( $this->TmpName );
		    
		    $width_orig = $image->getImageWidth();
		    $height_orig = $image->getImageHeight();
		    $image->setImageFormat('JPEG');
		    //http://php.net/manual/zh/imagick.constants.php#imagick.constants.filters
		    $image->setImageCompression(Imagick::COMPRESSION_JPEG);  
		    
		    $a = $image->getImageCompressionQuality() * 0.8;
		    if ($a == 0) {  $a = 80; }
		    $image->setImageCompressionQuality($a);
		    
            $ratio_orig = $width_orig/$height_orig;
            
            if ($this->newHeight && $this->newWidth/$this->newHeight > $ratio_orig) {
                $this->newWidth = intval($this->newHeight*$ratio_orig);
            } else {
                $this->newHeight = intval($this->newWidth/$ratio_orig);
            }
            
            if($width_orig < $this->newWidth && $height_orig < $this->newHeight){ //图片尺寸小，不会放大，
                //不返回，仍然进行处理。将图片的清晰度降低，压缩图片。
                $this->newWidth = $width_orig;
                $this->newHeight = $height_orig;
                $image->clear();
                $image->destroy();
                return false;
            }
            else{
                $image->resizeImage($this->newWidth,$this->newHeight,Imagick::FILTER_LANCZOS, 1);
            }
            
            $image->stripImage();
            $image->writeImage( $this->PicDir.DS.$this->FileName );
            $image->clear();
            $image->destroy();
            return true;
		}
		else {
			$normal  = imagecreatetruecolor($this->newWidth, $this->newHeight);
			$color=imagecolorallocate($normal,255,255,255);
			imagecolortransparent($normal,$color); //设置透明色，避免将部分png、gif图片的透明背景上传后变成黑色了。
			imagefill($normal,0,0,$color);
			
			if($ext == "gif") {
				$source = @imagecreatefromgif ($this->TmpName);
			}
			else if($ext == "png"){
				$this->ImageQuality = 9;
				$source = @imagecreatefrompng ($this->TmpName);
			}
			else if($ext == "jpg" || $ext == "jpeg") {
			    $source = @imagecreatefromjpeg($this->TmpName);
			}
			if( empty($source) ){
			    CakeLog::error('ImageResize::resize() error. image ext error. The ext is '.$ext);
			    return false;
			}
		
			$ret = @imagecopyresampled($normal, $source, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width_orig, $height_orig);
			@imagedestroy($source);
			if($ret){
				if($ext == "jpg" || $ext == "jpeg") {
					@imagejpeg($normal, $this->PicDir.DS.$this->FileName, "$this->ImageQuality");
				}
				else if($ext == "gif") {
					@imagegif ($normal, $this->PicDir.DS.$this->FileName);
				}
				else if($ext == "png") {
					@imagepng ($normal, $this->PicDir.DS.$this->FileName);
				}
				else{
					return false;
				}
				return true;
			}
			else{
				return false;
			}
		}
	}
}

?>
